<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text"
             v-model="name" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number"
             v-model.number="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="sex">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="flag ===false ? edit():hAdd()"> 添加/修改</button>
    </div>
    <div>
      <table border="1"
             cellpadding="10"
             cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="item in list"
            :key="item.id">
          <td>{{item.id}}</td>
          <td>{{item.name}}</td>
          <td>{{item.age}}</td>
          <td>{{item.sex}}</td>
          <td>
            <button @click="remove(item.id)">删除</button>
            <button @click="show(item.id)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data () {
    return {
      name: "",
      age: '',
      sex: '男',
      list: [
        { id: 1, name: "jkl", age: 199, sex: '男' },
        { id: 2, name: "tom", age: 34, sex: '女' },
        { id: 3, name: "jerry", age: 25.4, sex: '男' },
        { id: 4, name: "kuke", age: 19900, sex: '女' },
      ],
      flag: true,
      save: 0
    }
  },
  methods: {
    hAdd () {
      if ((this.name.length != '' && this.age != 0 && this.sex != '') || alert('请填写完整信息'))
      {
        this.list.push({
          id: this.list.length + 1,
          name: this.name,
          age: this.age,
          sex: this.sex
        });
      }
    },

    show (index) {
      this.flag = false
      console.log(this.flag);
      let aaa = this.list.findIndex(item => {
        return item.id === index
      });
      this.save = aaa;
      this.name = this.list[aaa].name;
      this.age = this.list[aaa].age;
      this.sex = this.list[aaa].sex;
    },

    edit () {
      if (!this.flag)
      {
        this.list[this.save].name = this.name;
        this.list[this.save].age = this.age;
        this.list[this.save].sex = this.sex;
        this.flag = true;
        console.log(this.flag);
      }
    },
    remove (index) {
      let aaa = this.list.findIndex(item => {
        return item.id === index;
      });
      this.list.splice(aaa,1);
    }
  }
}
</script>